

import { VotingContext, Candidate } from "../context/Voter";
import Style from "../styles/allowedVoter.module.css"
import React, { useCallback, useContext, useEffect, useState } from "react"
import { useDropzone, DropzoneOptions } from "react-dropzone";
import type { ICandidateForm } from "../types/voter";


import Image from "next/image";
import images from "../assets"
import Input from "../components/Input/Input";
import Button from "../components/Button/Button";
import Loader from "../components/Loader";
import { useRouter } from "next/router";

const candidateRegistation = () => {
    const [fileUrl, setFileUrl] = useState<string | null>(null);
    const [candidateForm, setcandidateForm] = useState<ICandidateForm>({
        name: "",
        address: "",
        age: "",
    });

    const {
        uploadToIPFSCandidate,
        setCandidate,
        getNewCandidate,
        candidateArray,
        loader,

    } = useContext(VotingContext);

    const router = useRouter();

    //-------------candidateS
    // useCallback缓存函数 
    // 里面的函数只会执行一次
    const onDrop = useCallback(async (acceptedFile: File[]) => {
        const url = await uploadToIPFSCandidate(acceptedFile[0]);
        setFileUrl(url || null)
    }, [])
    // React Dropzone 库来实现文件上传功能
    // 配置项补充类型，符合DropzoneOptionns 类型
    const dropzoneOptions: DropzoneOptions = {
        onDrop,
        accept: {
            "image/*": [],// 按类型要求，值是一个空数组（用于更细粒度 MIME 过滤，这里简单写）
        },
        maxSize: 5000000, // 5MB，注意单位是字节
    }

    const { getRootProps, getInputProps } = useDropzone(dropzoneOptions);
    //     getRootProps()：返回一个对象，包含用于设置上传区域根元素的属性（如样式、事件处理等）。
    // getInputProps()：返回一个对象，包含用于设置隐藏的 input 元素的属性（这个 input 元素用于处理文件选择对话框）。
    //     <div {...getRootProps()}>
    //     <input {...getInputProps()} />
    //     <p>拖放图片到这里，或者点击选择文件</p>
    // </div>

    useEffect(() => {
        getNewCandidate();
    }, []);

    return (
        <div className={Style.createVoter}>
            <div>
                {fileUrl && (
                    <div className={Style.voterInfo}>
                        <img src={fileUrl} alt="asset_file" />
                        <div className={Style.voterInfo_paragraph}>
                            <p>
                                Name: <span>&nbsp;{candidateForm.name}</span>
                            </p>
                            <p>
                                Add: <span>&nbsp;{(candidateForm.address as string).slice(0, 20)}</span>
                            </p>
                            <p>
                                Age: <span>&nbsp;{candidateForm.age}</span>
                            </p>
                        </div>
                    </div>
                )}

                {!fileUrl && (
                    <div className={Style.sideInfo}>
                        <div className={Style.sideInfo_box}>
                            <h4>Create Candidate For Voting</h4>
                            <p>
                                Blockchain voting orgainzation, privide ethereum blockchain eco
                                system
                            </p>
                            <p className={Style.sideInfo_para}>Contract Candidate List</p>
                        </div>
                        <div className={Style.car}>

                            {candidateArray.map((candidate: Candidate, index: number) => (
                                <div key={candidate.address || index} className={Style.card_box}>
                                    <div className={Style.image}>
                                        <img src={candidate.image} alt="Profile photo" />
                                    </div>
                                    <div className={Style.card_info}>
                                        <p>
                                            Age: {candidate?.age}
                                        </p>
                                        {/* 注意 */}
                                        <p>
                                            ID: #{candidate.candidateID}
                                        </p>
                                        <p>Address: {candidate?.address.slice(0, 7)}...</p>
                                    </div>
                                </div>
                            )).slice(0, 4)}

                        </div>

                    </div>
                )}
            </div>
            <div className={Style.voter}>
                <div className={Style.voter__container}>
                    <h1>Register New Candidate</h1>
                    <div className={Style.voter__container__box}>
                        <div className={Style.voter__container__box__div}>
                            <div {...getRootProps()}>
                                <input {...getInputProps()} />

                                <div className={Style.voter__container__box__div_info}>
                                    <p>Upload File: JPG, PNG, WEBM MAX 100MB</p>

                                    <div className={Style.voter__container__box__div__image}>
                                        <Image
                                            src={images.upload}
                                            width={150}
                                            height={150}
                                            objectFit="contain"
                                            alt="file upload"
                                        />

                                    </div>

                                    <p>Drog & Drop File</p>
                                    <p>or Browse media on your device</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className={Style.input__container}>
                    <Input
                        inputType="text"
                        title="Name"
                        placeholder="Candidate Name"
                        handleClick={(e) =>
                            setcandidateForm({
                                ...candidateForm,
                                name: e.target.value
                            })
                        }
                    />
                    <Input
                        inputType="text"
                        title="Address"
                        placeholder="Candidate Address"
                        handleClick={(e) =>
                            setcandidateForm({
                                ...candidateForm,
                                address: e.target.value
                            })
                        }
                    />

                    <Input
                        inputType="text"
                        title="Age"
                        placeholder="Candidate Age"
                        handleClick={(e) =>
                            setcandidateForm({
                                ...candidateForm,
                                age: e.target.value
                            })
                        }
                    />
                    <div className={Style.Button}>
                        <Button
                            btnName="Authorized candidate"
                            handleClick={() => setCandidate(candidateForm, fileUrl as string, router)}
                        />
                    </div>
                </div>
            </div>

            <div className={Style.createdVoter}>
                <div className={Style.createdVorter__info}>
                    <Image src={images.creator} alt="user profile" />
                    <p>Notice</p>
                    <p>
                        Organizer <span>0xf39Fd6e51..</span>
                    </p>
                    <p>
                        Only organizer of the voting contract can create candidate and candidate
                        for voting election
                    </p>
                </div>
            </div>
            {loader && <Loader />}
        </div>

    )
};

export default candidateRegistation;